import os
from settings import  *
import  cv2 as cv
FILE_SAVE_DIR =  r"D:\fileSave"
def get_save_path(boardIndex):
    '''
    保存图片的路径
    : param boardIndex: 图片的Id
    '''
    filePath = os.path.join(FILE_SAVE_DIR, "id_{}".format(boardIndex))
    if not os.path.exists(filePath):
        os.makedirs(filePath)
    return filePath


def get_image_index_by_path(imagePath):
    """
    根据图像目录,获取所有的图像编号
    :param imagePath: 图像的目录
    :return:
    """
    if not os.path.exists(imagePath):
        return []
    fileNames = []
    for root, dirs, files in os.walk(imagePath):
        for file in files:
            if root != imagePath:
                continue
            if file[-4:] != ".bmp":
                continue
            fileNames.append(file)

    indexList = []
    for fileName in fileNames:
        if "--" in fileName:
            indexFinded = fileName.split("--")[0]
            timeFinded = fileName.split("--")[1]
            indexList.append(indexFinded + "--" + timeFinded)
    return indexList


def get_image_by_image_path_and_image_index(findPath, indexTimeStr):
    """
    根据文件路径以及图像编号和时间去获取图片.
    :param findPath: 遍历的目录
    :param indexTimeStr: 图片名称,包含图像编号和时间的字符串.
    :return:
    """
    if not os.path.exists(findPath):
        return False, "查找的目录不存在", indexTimeStr
    fileNames = []
    for root, dirs, files in os.walk(findPath):
        for file in files:
            if root != findPath:
                continue
            if file[-4:] != ".bmp":
                continue
            fileNames.append(file)

    imageFinded = [fileName for fileName in fileNames if indexTimeStr in fileName]
    if len(imageFinded) > 0:
        imageNameFinded = imageFinded[0]
        filePath = os.path.join(findPath, imageNameFinded)
        image = cv.imread(filePath)
        return True, image, imageNameFinded
    else:
        return False, "{}的图像找不到".format(indexTimeStr), indexTimeStr


def get_debug_info_by_index(debugFilePath, boardIndex):
    """
    根据板的编号获取日志信息
    :param boardIndex: 板编号
    :return:
    """
    debugInfoWeb = ''
    filePath = os.path.join(get_save_path(boardIndex), "id_{}_debug.txt".format(boardIndex))
    with open(debugFilePath, encoding='utf-8') as f:
        while True:
            line = f.readline()
            if len(line) <= 0:
                break
            if "id_{}".format(boardIndex) not in line:
                continue
            debugInfoWeb = debugInfoWeb + line

        d = open(filePath, 'w', encoding="utf-8")
        d.write(debugInfoWeb)


def get_log_img_by_id(id_debug, txt_debug):
    # id_debug = "568"
    # txt_debug = "2021-07-19_debug.txt"
    ret_str = ""
    save_id_img_log_path = get_save_path(id_debug)
    debugFilePath = os.path.join(DEBUG_DIR, txt_debug)
    get_debug_info_by_index(debugFilePath, id_debug)
    id_time = "{}--{}".format(id_debug, txt_debug[:10])
    print(id_time)
    raw_ok = get_image_index_by_path(RAW_OK_DIR)
    print(raw_ok)
    raw_ok = sorted(raw_ok, key=lambda x: int(x.split("--")[0]))
    if id_time in raw_ok:
        res, image, imageName = get_image_by_image_path_and_image_index(RAW_OK_DIR, id_debug)
        if res:
            newImagePath = os.path.join(save_id_img_log_path, imageName)
            cv.imwrite(newImagePath, image)
        else:
            ret_str = ret_str + "识别成功的图片中,图像编号:{}的图像不存在".format(id_time)
    else:
        raw_fail = get_image_index_by_path(RAW_FAIL_DIR)
        raw_fail = sorted(raw_fail, key=lambda x: int(x.split("--")[0]))
        if id_time in raw_fail:
            res, image, imageName = get_image_by_image_path_and_image_index(RAW_FAIL_DIR, id_time)
            if res:
                newImagePath = os.path.join(save_id_img_log_path, imageName)
                cv.imwrite(newImagePath, image)
            else:
                ret_str = ret_str + "识别失败的图片中,图像编号:{}的图像不存在".format(id_time)
        else:
            ret_str = ret_str + "识别失败的图片中,图像编号:{}的图像不存在".format(id_time)

    raw_cut = get_image_index_by_path(RAW_CUT_LINE_DIR)
    raw_cut = sorted(raw_cut, key=lambda x: int(x.split("--")[0]))
    if id_time in raw_cut:
        res, image, imageName = get_image_by_image_path_and_image_index(RAW_CUT_LINE_DIR, id_time)
        if res:
            newImagePath = os.path.join(save_id_img_log_path, imageName)
            cv.imwrite(newImagePath, image)
        else:
            ret_str = ret_str + "切线图中图像编号:{}的图像不存在".format(id_time)
    else:
        ret_str = ret_str + "切线图中图像编号:{}的图像不存在".format(id_time)

    raw_begin_res = get_image_index_by_path(CUTTER_RAW_BEGIN_RES_DIR)
    raw_begin_res = sorted(raw_begin_res, key=lambda x: int(x.split("--")[0]))
    if id_time in raw_begin_res:
        res, image, imageName = get_image_by_image_path_and_image_index(CUTTER_RAW_BEGIN_RES_DIR, id_time)
        if res:
            newImagePath = os.path.join(save_id_img_log_path, imageName)
            cv.imwrite(newImagePath, image)
        else:
            ret_str = ret_str + "在铡刀起点检测结果图的文件夹中,图像编号:{}的图像不存在".format(id_time)
    else:
        ret_str = ret_str + "在铡刀起点检测结果图的文件夹中,图像编号:{}的图像不存在".format(id_time)

    raw_final_res = get_image_index_by_path(CUTTER_RAW_FINAL_RES_DIR)
    raw_final_res = sorted(raw_final_res, key=lambda x: int(x.split("--")[0]))
    if id_time in raw_final_res:
        res, image, imageName = get_image_by_image_path_and_image_index(CUTTER_RAW_FINAL_RES_DIR, id_time)
        if res:
            newImagePath = os.path.join(save_id_img_log_path, imageName)
            cv.imwrite(newImagePath, image)
        else:
            ret_str = ret_str + "在铡刀终点检测结果图的文件夹中,图像编号:{}的图像不存在".format(id_time)
    else:
        ret_str = ret_str + "在铡刀终点检测结果图的文件夹中,图像编号:{}的图像不存在".format(id_time)

    return ret_str

def get_alarm_index(textDebug):
    debugFilePath  =os.path.join(DEBUG_DIR, textDebug)
    indexList = []
    with open(debugFilePath, encoding='utf-8') as f:
        while True:
            line = f.readline()
            if len(line) <= 0:
                break
            if "两拼板，终点检测: 验证出错,弹窗提示工人操作"  in line:
                infos = line.split(" ")
                try:
                    info = [x for x in infos if x.__contains__("id")][0].split('_')[1]
                    indexList.append(info)
                except:
                    pass
        print(indexList)
        return indexList

if __name__ == '__main__':
    debugFile = "2024-04-13_YiLiAnDa_debug.txt"
    indexList = get_alarm_index(debugFile)
    for index in indexList:
        get_log_img_by_id(index,debugFile)